import router from '@/router/index.ts'
import {
    getJWTToken,
    removeJWTToken,
  } from '@/utils/tokens'
import store from '@/store/index.ts'


const whiteList = ['/pages/login', '/auth-redirect']

// import app from "@/main.ts"

router.beforeEach((to: any, from: any, next: any) => {

    // console.log("from",from)
    // console.log("to",to)
    // console.log("vue",vue)

    // 离线模式
    
    // let isOffline = app.config.globalProperties.$offline;
    let isOffline = false;
    // console.log("isOffline",isOffline)
    if(isOffline){
      if(to.path == "/"){
        next('/dashboard');
      }
      else {
        next();
      } 
      console.log("isOffline true",isOffline)
      return;
    }

    if(to.path.name != "Login"){
      console.log("to.query",to.query)
      let tabsInfo = {
        path: to.path,
        query: to.query,
        title:to.name,
      }
      store.commit("managercore/tabs/PathChange", to.path);
      store.commit("managercore/tabs/AddTabsInfo", tabsInfo);
    }


    // NProgress.start(); // start progress bar
  
    if (getJWTToken()) {
      store
        .dispatch("managercore/profiles/GetUserInfo")
        .then((response: any) => {

          console.log("has load user info")

          // 获取菜单
          store
            .dispatch("managercore/menus/loadMenu")
            .then((r:any) =>{
              // console.log("has load menu info")
            
              if (to.path === '/pages/login') {
                // NProgress.done();
                next({
                  path: 'dashboard'
                });
              } 
              else if (to.path === '/'){
    
                next({
                  path: 'dashboard'
                });
              }
              else{
                // console.log(3333)
                next();
              }


            })           
            .catch((e:any)=>{
              // console.log(e);
              removeJWTToken();
              next({
                path: '/'
              });
            }) 


        })
        .catch((error: any) => {
          // console.log(error);
          removeJWTToken();
          next({
            path: '/'
          });
        })
    } else {
      console.log("没有本地缓存");
  
      if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
        next()
      } else {
        next(`/pages/login?redirect=${to.path}`) // 否则全部重定向到登录页
        // NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
      }
    }
  })
  
  